package com.point_of_sale.terminal;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.point_of_sale.cart.Cart;
import com.point_of_sale.product.Product;
import com.point_of_sale.product_loader.PlainTextProductLoader;
import com.point_of_sale.product_loader.ProductLoader;

public class Terminal 
{
	private ProductLoader loader;
	private HashMap<String, Product> products;
	private Cart shoppingCart;
	
	public Terminal()
	{
		clearCart();
	}
	
	private void clearCart()
	{
		shoppingCart = new Cart();
	}
	
	public void loadProducts(String location) throws NoProductListLoaderException
	{
		// Obviously, if we had other ProductLoader implementations then we could check to see
		// if it was an XML, CSV, etc. Also, for simplicity's sake I assumed every plain text file would 
		// end in .txt. This obviously would not be necessarily true in the Unix world
		if(location.contains(".txt"))
		{
			loader = new PlainTextProductLoader();
			products = loader.getProducts(location);
		}
		else
		{
			throw new NoProductListLoaderException("There is no implementation for a ProductLoader with that format");
		}
	}

	public void scan(String productCode)
	{
		shoppingCart.addItem(productCode);
	}
	
	public BigDecimal checkOut()
	{
		// I'm using BigDecimal instead of a primitive type because I find it easier to have two decimal places always appear with BigDecimal
		// then with a primitive type
		BigDecimal total = new BigDecimal(0);
		
		Iterator<Entry<String, Product>> iter = products.entrySet().iterator();
		
		while(iter.hasNext())
		{
			Entry<String, Product> entry = iter.next();
			Product p = entry.getValue();
			String productCode = entry.getKey();
			
			if(shoppingCart.getQuantity(productCode) != null)
			{
				total = total.add(new BigDecimal(p.getPrice(shoppingCart.getQuantity(productCode))));
			}
		}

		total = total.setScale(2, BigDecimal.ROUND_HALF_EVEN);
		
		clearCart();
		
		return total;
	}

	
}
